<?php
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP
 *
 * This content is released under the MIT License (MIT)
 *
 * Copyright (c) 2014 - 2017, British Columbia Institute of Technology
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @package	CodeIgniter
 * @author	EllisLab Dev Team
 * @copyright	Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
 * @copyright	Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
 * @license	http://opensource.org/licenses/MIT	MIT License
 * @link	https://codeigniter.com
 * @since	Version 1.0.0
 * @filesource
 */
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * CodeIgniter CAPTCHA Helper
 *
 * @package		CodeIgniter
 * @subpackage	Helpers
 * @category	Helpers
 * @author		EllisLab Dev Team
 * @link		https://codeigniter.com/user_guide/helpers/captcha_helper.html
 */

// ------------------------------------------------------------------------

if ( ! function_exists('create_captcha'))
{
	/**
	 * Create CAPTCHA
	 *
	 * @param	array	$data		data for the CAPTCHA
	 * @param	string	$img_path	path to create the image in
	 * @param	string	$img_url	URL to the CAPTCHA image folder
	 * @param	string	$font_path	server path to font
	 * @return	[]
	 */
	function create_captcha($data = '', $img_path = '', $img_url = '', $font_path = '')
	{
		$defaults = array(
			'img_path'	=> '',
			'img_url'	=> '',
			'img_width'	=> '150',
			'img_height'	=> '30',
			'font_path'	=> '',
			'expiration'	=> 7200,
			'word_length'	=> 4,
			'dot_num'   => 200,
			'line_num'  => 5,
			'font_size'	=> 16,
			'img_id'	=> '',
			'pool'		=> '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
			'colors'	=> array(
				'background'=> [255, 255, 255],
				'text'		=> [0, 0, 0],
			)
		);
        $configArr = require_once CONFIGPATH.'captcha.php';
		foreach ($defaults as $key => $val) {
            $$key = isset($configArr[$key]) ? $configArr[$key] : $val; //数组转变量
		}

        $data && extract($data);//数组转变量 转的666
/*        foreach ($data as $key2 => $val2) {
            $$key2 = $val2; //数组转变量
        }*/

		//如果$img_path为空 或者 $img_url为空 或者 $img_path不是目录 或者 $img_path无写权限 或者 gd库不存在
		if ($img_path === '' OR $img_url === ''
			OR ! is_dir($img_path) OR ! is_really_writable($img_path)
			OR ! extension_loaded('gd')){
			return FALSE;
		}

		$now = microtime(TRUE);

		$current_dir = @opendir($img_path);

		while ($filename = @readdir($current_dir))
		{
		    //遍历目录下的所有验证码文件
		    //取出文件名的最后四个字符 如果是.jpg或.png
            //将.jpg和.png替换为空 加上$expiration保存时间 如果小于当前时间  则删除
			if (in_array(substr($filename, -4), array('.jpg', '.png'))
				&& (str_replace(array('.jpg', '.png'), '', $filename) + $expiration) < $now)
			{
				@unlink($img_path.$filename);
			}
		}
		@closedir($current_dir);

        $pool_length = mb_strlen($pool);
        $rand_max = $pool_length - 1;

        $word_length > 6 && $word_length = 6;


        // PHP7 or a suitable polyfill
        //random_int PHP7新增更好的随机数函数 代替mt_rand()  被我咔嚓了  写的什么傻逼源码

        $word = '';
        for($i = 0; $i < $word_length; $i++){
            $word .= mb_substr($pool,rand(0,$rand_max),1);
        }

		$im = function_exists('imagecreatetruecolor')
			? imagecreatetruecolor($img_width, $img_height)
			: imagecreate($img_width, $img_height);


		is_array($colors) OR $colors = $defaults['colors'];

		foreach (array_keys($defaults['colors']) as $key)
		{
			// Check for a possible missing value
			is_array($colors[$key]) OR $colors[$key] = $defaults['colors'][$key];
			$colors[$key] = imagecolorallocate($im, $colors[$key][0], $colors[$key][1], $colors[$key][2]);
		}

		// Create the rectangle  画矩形
		//ImageFilledRectangle($im, 0, 0, $img_width, $img_height, $colors['background']);
		imagefill($im,0,0,$colors['background']);


		$use_font = ($font_path !== '' && file_exists($font_path) && function_exists('imagettftext'));

        if ($use_font === FALSE) {
            //英文
            for ($i = 0; $i < $word_length; $i++)
            {
                $x = 10+$i*25+rand(3,20);
                $y = rand(0,$img_height-20);
                imagestring($im, $font_size, $x, $y, $word[$i], $colors['text']);
            }
        } else {
            //中文
            ($font_size > 30) && $font_size = 30;
            for ($i = 0; $i < $word_length; $i++) {
                $x = 10+$i*25+rand(3,20);
                $y = mt_rand($img_height / 3, $img_height - 3);
                $s = mb_substr($word,$i,1);
                imagettftext($im, $font_size, 0, $x, $y, $colors['text'], $font_path, $s);
            }
        }

        //添加点
        for($i = 0;$i<$dot_num;$i++){
            $fontcolor = imagecolorallocate($im,rand(50,200),rand(50,200),rand(50,200));
            imagesetpixel($im,rand(1,$img_width),rand(1,$img_height),$fontcolor);
        }

        //添加线
        for($i = 0;$i<$line_num;$i++){
            $fontcolor = imagecolorallocate($im,rand(50,200),rand(50,200),rand(50,200));
            imageline($im,rand(1,$img_width),rand(1,$img_height),rand(1,$img_width),rand(1,$img_height),$fontcolor);
        }

		// -----------------------------------
		//  Generate the image
		// -----------------------------------
		$img_url = rtrim($img_url, '/').'/';

		if (function_exists('imagepng')) {
            $img_filename = $now.'.png';
            imagepng($im, $img_path.$img_filename);
		}elseif (function_exists('imagejpeg')) {
            $img_filename = $now.'.jpg';
            imagejpeg($im, $img_path.$img_filename);
		}else {
			return FALSE;
		}

		$url = $img_url.$img_filename;
		$img = '<img class="captcha_img" src="'.$url.'" style="width: '.$img_width.'; height: '.$img_height .'; border: 0;" alt=" " />';
        imagedestroy($im);

        $_SESSION['captcha_img'] = strtolower($word);

		return ['word' => $word, 'time' => $now, 'image' => $img, 'filename' => $img_filename,'url'=>$url];
	}
}
